package com.example.assignment5.service;


import com.example.assignment5.exception.CustomException;
import com.example.assignment5.commodity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class CommodityServiceI implements CommodityService {

    @Autowired
    com.example.assignment5.repository.commodityRepository commodityRepository;

    @Override
    public void add(commodity commodity) {
        List<com.example.assignment5.commodity> commodities=commodityRepository.findCommodityByName(commodity.getName());
        if(commodities.size()!=0){
            throw new CustomException("已存在");
        }
        commodityRepository.save(commodity);
    }

    @Override
    public void deleteById(Long id) {
        commodity commodity=commodityRepository.findById(id).orElse(null);
        if(commodity==null){
            throw new CustomException("不存在");
        }
        commodityRepository.deleteById(id);
    }

    @Override
    public void updateById(commodity commodity) {
        com.example.assignment5.commodity commodity1=commodityRepository.findById(commodity.getId()).orElse(null);
        if(commodity1==null){
            throw new CustomException("不存在");
        }
        commodityRepository.save(commodity);
    }

    @Override
    public commodity getById(Long id) {
        return commodityRepository.findById(id).orElse(null);
    }

    @Override
    public List<commodity> getAll() {
        return commodityRepository.findAll();
    }

    @Override
    public List<commodity> getByName(String name) {
        return commodityRepository.findCommodityByName(name);
    }

    @Override
    public List<commodity> getByNameContaining(String name) {
        return commodityRepository.findCommodityByNameContaining(name);
    }




}
